package com.tarena.lbs.business.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.pojo.dto.StoreDTO;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class StoreRepositoryImpl implements StoreRepository{
    @Autowired
    private StoreMapper storeMapper;


    @Override
    public List<StorePO> findByBusinessId(Integer businessId) {
        log.debug("根据商家ID查询店铺列表，入参：{}", businessId);
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id", businessId);
        return storeMapper.selectList(queryWrapper);
    }

    @Override
    public PageResult<StorePO> pageList(StoreQuery query) {
        log.debug("分页查询店铺列表，入参：{}", query);
        QueryWrapper<StorePO> queryWrapper = assmbleStoreQuery(query);

        // 计算总数
        long total = storeMapper.selectCount(queryWrapper);
        // 分页查询
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<StorePO> storePOs = storeMapper.selectList(queryWrapper);

        // 构建返回结果
        PageResult<StorePO> pageResult = new PageResult<>();
        pageResult.setObjects(storePOs);
        pageResult.setTotal(total);
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        return pageResult;
    }
    /**
     * 将前端请求拼接成查询条件
     */
    private QueryWrapper<StorePO> assmbleStoreQuery(StoreQuery query) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();

        if (query.getBusinessId() != null) {
            queryWrapper.eq("business_id", query.getBusinessId());
        }
        //门店名称模糊查询
        if (query.getStoreName() != null && !query.getStoreName().isEmpty()) {
            queryWrapper.like("store_name", query.getStoreName());
        }
        //负责人联系方式模糊查询
        if (query.getStoreHeadPhone() != null && !query.getStoreHeadPhone().isEmpty()) {
            queryWrapper.like("store_head_phone", query.getStoreHeadPhone());
        }
        //店铺状态查询，默认排除 storeStatus=2
        if (query.getStoreStatus() != null) {
            queryWrapper.eq("store_status", query.getStoreStatus());
        } else {
            queryWrapper.ne("store_status", 2);
        }
        //省市区条件
        if (query.getProvinceId() != null) {
            queryWrapper.eq("province_id", query.getProvinceId());
        }
        if (query.getCityId() != null) {
            queryWrapper.eq("city_id", query.getCityId());
        }
        if (query.getAreaId() != null) {
            queryWrapper.eq("area_id", query.getAreaId());
        }

        //创建时间范围
        if (query.getStartingTime() != null) {
            queryWrapper.ge("create_time", query.getStartingTime());
        }
        if (query.getEndTime() != null) {
            queryWrapper.le("create_time", query.getEndTime());
        }

        //排序逻辑
        queryWrapper.orderByDesc("create_time");
        queryWrapper.orderByDesc("id");

        return queryWrapper;
    }


    @Override
    public void saves(StorePO po) {
        log.debug("保存店铺数据，入参：{}", po);
        storeMapper.insert(po);
    }

    @Override
    public StorePO saveStore(StorePO po) {
        storeMapper.insert(po);
        return po;
    }

    @Override
    public List<StorePO> getStoreByCity(AreaStoreQuery query) {
        log.debug("根据区域查询店铺，查询参数: {}", query);
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        
        // 默认排除已删除的店铺
        queryWrapper.ne("store_status", 2);
        
        List<Long> cityIdList = query.getCityIdList();
        Integer level = query.getLevel();
        
        // 检查参数有效性
        if(level != null && cityIdList != null && !cityIdList.isEmpty()){
            if(level == 1){
                queryWrapper.in("province_id", cityIdList);
                log.debug("按省级ID查询，provinceIds: {}", cityIdList);
            } else if(level == 2){
                queryWrapper.in("city_id", cityIdList);
                log.debug("按市级ID查询，cityIds: {}", cityIdList);
            } else if(level == 3){
                queryWrapper.in("area_id", cityIdList);
                log.debug("按区级ID查询，areaIds: {}", cityIdList);
            } else {
                log.warn("区域级别无效: {}, 有效范围[1-3]", level);
            }
        } else {
            // 记录更详细的警告信息，包括调用堆栈摘要
            String stackTrace = Arrays.stream(Thread.currentThread().getStackTrace())
                    .limit(5)
                    .map(StackTraceElement::toString)
                    .collect(Collectors.joining("\n"));
            log.warn("区域查询参数不完整：level={}, cityIdList={}\n调用栈: {}", 
                     level, cityIdList, stackTrace);
        }
        
        List<StorePO> poList = storeMapper.selectList(queryWrapper);
        log.debug("区域查询结果数量：{}", poList != null ? poList.size() : 0);
        return poList;
    }

    @Override
    public void update(StorePO po){
        storeMapper.updateById(po);
    }

    @Override
    public StorePO storeEdit(Integer id){
        return storeMapper.selectById(id);
    }
    @Override
    public List<StorePO> getStoreById(AreaStoreQuery query) {
        log.debug("根据ID列表查询店铺，入参：{}", query);
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();

        // 使用storeIdList进行查询
        List<Long> storeIdList = query.getStoreIdList();
        if (storeIdList != null && !storeIdList.isEmpty()) {
            queryWrapper.in("id", storeIdList);
        } else {
            log.warn("店铺ID列表为空");
            return Collections.emptyList();
        }

        // 默认排除状态为2的店铺
        queryWrapper.ne("store_status", 2);

        // 按创建时间和ID降序排序
        queryWrapper.orderByDesc("create_time");
    queryWrapper.orderByDesc("id");

        List<StorePO> poList = storeMapper.selectList(queryWrapper);
        log.debug("ID列表查询结果数量：{}", poList != null ? poList.size() : 0);
        return poList;
    }
}

